package com.xc.utils.redis;

import com.xc.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  客户端cookie实用工具
 * Created by xiongcan on 2018/1/22.
 */
@Slf4j
public class CookieUtils {

    //  一级域名下的cookie，一级下的二级才能访问到，同级的访问不到
    private final static String COOKIE_DOMAIN = PropertiesUtil.getProperty("cookie.project.url");

    //  写入cookie
    public static void writeLoginToken(HttpServletResponse httpServletResponse, String token, String COOKIE_NAME){
        Cookie cookie = new Cookie(COOKIE_NAME,token);

//        cookie.setDomain(COOKIE_DOMAIN);
        //  设置在根目录下
        cookie.setPath("/");
        // MaxAge为cookie的有效期（单位秒），如果不设置，那cookie不会写入硬盘，只会写入内存，只在当前页面有效
        cookie.setMaxAge(60 * 60 * 24 * 365); //  -1为永久的
        //  防止脚本攻击带来的信息泄漏的风险，不允许脚本访问cookie
        cookie.setHttpOnly(true);
        log.info("write cookie name :{} ,cookie value : {}" , cookie.getName() , cookie.getValue());
        httpServletResponse.addCookie(cookie);
    }

    //  读取cookie
    public static String readLoginToken(HttpServletRequest httpServletRequest, String COOKIE_NAME){
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            for (Cookie ck : cookies){
//                log.info("[readLoginToken]cookie name : {} ,cookie value : {}" , ck.getName() , ck.getValue());
                if(StringUtils.equals(ck.getName() , COOKIE_NAME)){
//                    log.info("[readLoginToken]return cookie value : {}" ,  ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    //  删除cookie的方法
    public static void delLoginToken(HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse, String COOKIE_NAME){
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            for (Cookie ck : cookies){
                if(StringUtils.equals(ck.getName() , COOKIE_NAME)){
//                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    ck.setMaxAge(0);    //  如果设置有效期为0，即为删除cookie
                    log.info("del cookie name : {} ,cookie value : {}" , ck.getName() , ck.getValue());
                    httpServletResponse.addCookie(ck);
                    return;
                }
            }
        }
    }




}
